﻿using System.Collections.ObjectModel;
using MyTinnyApi.model;
using MyTinnyApi.util;
using Newtonsoft.Json;
using TreeView.Maui.Core;
using CommunityToolkit.Maui.Alerts;

namespace MyTinnyApi;

public partial class MainPage : ContentPage
{
    private List<TreeViewNode> FoldersListFlat = new List<TreeViewNode>();
    private List<Requests> RequestsList = new List<Requests>();
    public ObservableCollection<TreeViewNode> FoldersList { get; set; }

	private ObservableCollection<string> _bread;
	public ObservableCollection<string> Bread
	{
		get
		{
			return _bread;
		}
		set
		{
			_bread = value;
			OnPropertyChanged(nameof(Bread));
		}
	}

	private RequestTab _req;
	public RequestTab CurrentRequestTab
	{
		get { return _req; }
		set
		{
			_req = value;
			if (!value.Request.InitedFullInfo)
			{
				_req.Request = RequestUtil.GetRequestsById(_req.Request.Id);
			}
			//RequestLayout.RequestSource = value;
			OnPropertyChanged(nameof(CurrentRequestTab));
		}
	}

    private ObservableCollection<RequestTab> _reqList;
    public ObservableCollection<RequestTab> OpenedRequestTabList
    {
        get { return _reqList; }
        set
        {
            _reqList = value;
            //RequestLayout.RequestSource = value;
            OnPropertyChanged(nameof(OpenedRequestTabList));
        }
    }

    private ObservableCollection<Env> _envList;
    public ObservableCollection<Env> EnvList
    {
        get { return _envList; }
        set
        {
            _envList = value;
			//RequestLayout.RequestSource = value;
			
            OnPropertyChanged(nameof(EnvList));
        }
    }

	private Env _selectedEnv;
	public Env SelectedEnv
	{
		get
		{
			return _selectedEnv;
		}
		set
		{
            _selectedEnv = value;
			OnPropertyChanged(nameof(SelectedEnv));
		}
	}

    private int _selectedEnvIndex;
    public int SelectedEnvIndex
    {
        get
        {
            return _selectedEnvIndex;
        }
        set
        {
            _selectedEnvIndex = value;
			if(value >= 0 && value < EnvList.Count)
			{
				SelectedEnv = EnvList[value];
			}
            OnPropertyChanged(nameof(SelectedEnvIndex));
        }
    }

    public MainPage()
	{
		InitializeComponent();


		FoldersList = new ObservableCollection<TreeViewNode>(LoadFolderTree());
		EnvList = new ObservableCollection<Env>(EnvUtil.GetAllEnv());
		SelectedEnvIndex = 0;

		BindingContext = this;

		//Dispatcher.DispatchAsync(() =>
		//{
		//});
		//try
		//{
  //          //ImportExportUtil.ImportPostman("/Users/zhangming/Documents/postman/jsh-new-test.postman_environment.json", ApiConstants.import_postman_env);
  //          ImportExportUtil.ImportPostman("/Users/zhangming/Documents/postman/巨商汇.postman_collection.json", ApiConstants.import_postman_collection);
  //          Toast.Make("Import success").Show();
		//}
		//catch (Exception ex)
		//{
		//	Toast.Make(ex.Message).Show();
		//}
	}

    /// <summary>
    /// 加载左侧目录树
    /// </summary>
    /// <returns></returns>
    private List<TreeViewNode> LoadFolderTree()
	{
		FoldersListFlat = DbUtil.ExecuteReaderForType<TreeViewNode>("select * from t_folders order by ShowOrder");
        var rootFolders = FoldersListFlat.Where(f => f.ParentId == null).ToList();

        RequestsList = DbUtil.ExecuteReaderForType<Requests>("select * from t_request order by ShowOrder");

		var config = AppConfig.GetConfig();
		var openedRequestsList = RequestsList.Where(req => config.OpenedRequestIds.Contains(req.Id)).ToList();

		var activedReqId = config.ActivedRequest;

		OpenedRequestTabList = new ObservableCollection<RequestTab>(openedRequestsList.Select(r => new RequestTab() { Request = r, Actived = r.Id == activedReqId }));

        foreach (var folder in rootFolders)
		{
			folder.Level = 0;
			FindChildren(folder, 1);
		}

		return rootFolders;
	}

	/// <summary>
	/// 组装目录树
	/// </summary>
	/// <param name="folder"></param>
	/// <param name="folders"></param>
	private void FindChildren(TreeViewNode folder, int level)
	{
		var childFolders = FoldersListFlat.Where(f => folder.Id == f.ParentId).ToList();
		var childRequests = RequestsList.Where(r => folder.Id == r.FolderId).ToList();

		if(childFolders?.Count > 0)
		{
			foreach (var cFolder in childFolders)
			{
				cFolder.Level = level;
				folder.Children.Add(cFolder);
				FindChildren(cFolder, level + 1);
			}
		}
		if(childRequests?.Count > 0)
		{
			foreach(var req in childRequests)
			{
				folder.Children.Add(new TreeViewNode() { Id = req.Id, Name = req.RequestName, Level = level, ParentId = folder.Id, NodeType = 1 });
			}
		}
	}

    /// <summary>
	/// 点击左侧树控件的方法
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
    void TreeNodeTapped(System.Object sender, Microsoft.Maui.Controls.TappedEventArgs e)
    {
		var label = sender as Label;
		var param = e.Parameter as TreeViewNode;
		if(param.NodeType == 1)
		{
            foreach (var rt in OpenedRequestTabList)
			{
				rt.Actived = false;
			}
			//是一个request
			var reqTabList = OpenedRequestTabList.Where(r => r.Request.Id == param.Id).ToList();
			if(reqTabList.Count == 0)
			{
				var request = RequestUtil.GetRequestsById(param.Id.Value);
                CurrentRequestTab = new RequestTab() { Request = request, Actived = true };
				OpenedRequestTabList.Add(CurrentRequestTab);
			}
			else
			{
                CurrentRequestTab = reqTabList[0];
                CurrentRequestTab.Actived = true;
			}
			InitBreadLayout();
		}
    }

	void InitBreadLayout()
	{
		var bread = new List<string>();
		int? id = CurrentRequestTab.Request.FolderId;

		bread.Add(CurrentRequestTab.Request.RequestName);
		while (true)
		{
			var treeViewNode = FoldersListFlat.Find(f => f.Id == id);
			if(treeViewNode == null)
			{
				break;
			}
			bread.Add("/");
			bread.Add(treeViewNode.Name);
			id = treeViewNode.ParentId;
			if(id == null)
			{
				break;
			}
		}

		bread.Reverse();
		Bread = new ObservableCollection<String>(bread);

		//var BreadLayout = new StackLayout();
  //      BreadLayout.Children.Clear();

		//int fontSize = 20;

		//BreadLayout.Children.Add(new Label() { Text = "Http", FontSize = fontSize });

		//bread.ForEach(b =>
		//{
  //          BreadLayout.Children.Add(new Label() { Text = " / ", FontSize = fontSize });
  //          BreadLayout.Children.Add(new Label() { Text = b, FontSize = fontSize });
		//});
	}

	/// <summary>
	/// 标签页按钮点击事件
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
    void TabButtonClicked(System.Object sender, System.EventArgs e)
    {
		var button = sender as Button;
		var reqTab = button.CommandParameter as RequestTab;
		CurrentRequestTab = reqTab;
        InitBreadLayout();
    }

	/// <summary>
	/// 导入按钮点击
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	async void ImportButtonClicked(System.Object sender, System.EventArgs e)
	{
		var options = new PickOptions();
		//options.FileTypes = new FilePickerFileType(new Dictionary<DevicePlatform, IEnumerable<string>>
		//		{
		//			//{ DevicePlatform.iOS, new[] { "public.json" } },
		//			//{ DevicePlatform.Android, new[] { "application/json" } },
		//			{ DevicePlatform.macOS, new[] { "public.json" } },
		//			{ DevicePlatform.WinUI, new[] { "JSON Files (*.json)", "*.json" } }
		//		});
		var file = await FilePicker.PickAsync(options);
		if (file != null)
		{
			// 处理选择的文件
			// 在这里可以使用file.Path获取文件的路径
			// 例如：var filePath = file.Path;
			var filePath = file.FullPath;
		}
	}

    void SubTabButtonClick(System.Object sender, System.EventArgs e)
    {
		var button = sender as Button;
		var flag = int.Parse(button.CommandParameter.ToString());
		CurrentRequestTab.Request.CurrentShow = flag;
    }

    async void SendButtonClicked(System.Object sender, System.EventArgs e)
    {
		var result = await HttpUtil.SendHttpRequest(CurrentRequestTab.Request);
		CurrentRequestTab.Request.ResponseText = result;
    }

  //  void EnvSelectedChanged(System.Object sender, System.EventArgs e)
  //  {
		//var picker = sender as Picker;
		//SelectedEnvIndex = picker.SelectedIndex;
  //  }
}


